﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO;

namespace TicketService.Client.Common
{
    public class Log
    {
        private static Queue<string> q = null;
        private Thread writeThread = null;
        private static object o = new object();
        private Log()
        {
            q = new Queue<string>();
            writeThread = new Thread(new ThreadStart(WriteMsg));
            writeThread.IsBackground = true;
            writeThread.Name = "写日志线程";
            writeThread.Start();
        }
        /// <summary>
        /// 日志类
        /// </summary>
        private static Log log = new Log();
        /// <summary>
        /// 获取实例
        /// </summary>
        public static Log Instance
        {
            get { return log; }
        }
        /// <summary>
        /// 声明委托变量、执行写入日志方法
        /// </summary>
        private static Action<string> writeAction = new Action<string>((str) =>
        {
            log.WriteToLog(str);
        });
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="Message">日志内容</param>
        public void ThreadWriteLog(string Message)
        {
            lock (o)
            {
                q.Enqueue(Message);
                Monitor.Pulse(o);
            }
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="Message">日志内容</param>
        public static void WriteLog(string Message)
        {
            writeAction.Invoke(Message);
        }
        /// <summary>
        /// 写入日志文件
        /// </summary>
        /// <param name="Message">日志内容</param>
        private void WriteToLog(string Message)
        {
            try
            {
                string strDirectoryFile = AppDomain.CurrentDomain.BaseDirectory + "\\log\\";
                if (!Directory.Exists(strDirectoryFile))
                {
                    Directory.CreateDirectory(strDirectoryFile);
                }
                string strFile = DateTime.Now.Date.ToString("yyyyMMdd");
                using (FileStream stream = new FileStream(strDirectoryFile + strFile + ".log", FileMode.Append))
                {
                    StreamWriter writer = new StreamWriter(stream);
                    writer.WriteLine(DateTime.Now + "   " + Message);
                    writer.Close();
                    writer.Dispose();
                }
            }
            catch { }
        }
        /// <summary>
        /// 写消息
        /// </summary>
        private void WriteMsg()
        {
            while (true)
            {
                lock (o)
                {
                    while (q.Count == 0)
                    {
                        Monitor.Wait(o);
                    }
                    WriteToLog(q.Dequeue());
                }
            }

        }
    }
}
